package com.nut.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Slf4j
public class EncryptUtil {

    public static final String ERROR = "encrypt_error";

    public final static byte[] MD5(String str) {
        try {
            byte[] res = str.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5".toUpperCase());
            mdTemp.update(res);
            byte[] hash = mdTemp.digest();
            return hash;
        } catch (Exception e) {
            log.error(ERROR, e);
            return null;
        }
    }


    public static String JM(byte[] inStr) {
        String newStr = new String(inStr);
        char[] a = newStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String k = new String(a);
        return k;
    }

    public static String BASE64Encrypt(byte[] key) {
        String edata = null;
        try {
            edata = (new BASE64Encoder()).encodeBuffer(key).trim();
        } catch (Exception e) {
            log.error(ERROR, e);
        }
        return edata;
    }


    public static byte[] BASE64Decrypt(String data) {
        if (data == null) {
            return null;
        }
        byte[] edata = null;
        try {
            edata = (new BASE64Decoder()).decodeBuffer(data);
            return edata;
        } catch (Exception e) {
            log.error(ERROR, e);
        }
        return null;
    }


    public static byte[] DES3Encrypt(String key, String str) {
        byte[] newkey = key.getBytes();
        SecureRandom sr = new SecureRandom();
        DESedeKeySpec dks = null;
        try {
            dks = new DESedeKeySpec(newkey);
        } catch (InvalidKeyException e) {
            log.error(ERROR, e);
        }

        SecretKeyFactory keyFactory = null;
        try {
            keyFactory = SecretKeyFactory.getInstance("DESede");
        } catch (NoSuchAlgorithmException e) {
            log.error(ERROR, e);
        }

        SecretKey securekey = null;
        try {
            securekey = keyFactory.generateSecret(dks);
        } catch (InvalidKeySpecException e) {
            log.error(ERROR, e);
        }

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            log.error(ERROR, e);
        } catch (NoSuchPaddingException e) {
            log.error(ERROR, e);
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        } catch (InvalidKeyException e) {
            log.error(ERROR, e);
        }
        byte[] bt = new byte[0];
        try {
            bt = cipher.doFinal(str.getBytes("utf-8"));
        } catch (IllegalBlockSizeException e) {
            log.error(ERROR, e);
        } catch (BadPaddingException e) {
            log.error(ERROR, e);
        } catch (UnsupportedEncodingException e) {
            log.error(ERROR, e);
        }
        return bt;
    }


    public static String DES3Decrypt(byte[] edata, String key) {
        String data = "";
        try {
            if (edata != null) {
                byte[] newkey = key.getBytes();
                DESedeKeySpec dks = new DESedeKeySpec(newkey);
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
                SecretKey securekey = keyFactory.generateSecret(dks);
                Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, securekey, new SecureRandom());
                byte[] bb = cipher.doFinal(edata);
                data = new String(bb, "UTF-8");
            }
        } catch (Exception e) {
            log.error(ERROR, e);
        }
        return data;
    }


    public static String getSign(Map<String, Object> paramMap, String tokenKey) {
        List<String> paramList = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            if ("sign".equals(key) || "Sign".equals(key)) {
                continue;
            }
            String value = (String) entry.getValue();
            paramList.add(key.toLowerCase() + "=" + value.toLowerCase());
        }

        Collections.sort(paramList);
        StringBuilder paramBuilder = new StringBuilder();
        for (String param : paramList) {
            paramBuilder.append(param);
        }

        String blankParam = paramBuilder.toString().toLowerCase();

        blankParam += tokenKey.toLowerCase();

        String sign = "";
        try {
            sign = mdd5(blankParam, true);
        } catch (NoSuchAlgorithmException e) {
            log.error(ERROR, e);
        }
        return sign;
    }

    private static String mdd5(String key, boolean isUp) throws NoSuchAlgorithmException {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(key.getBytes(StandardCharsets.UTF_8));
            byte[] data = md.digest();
            int index;
            for (byte b : data) {
                index = b;
                if (index < 0) {
                    index += 256;
                }
                if (index < 16) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(index));
            }
            if (isUp) {
                return sb.toString().toUpperCase();
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(ERROR, e);
        }
        return sb.toString();
    }

}
